<?php
/**
 * Created by PhpStorm.
 * User: sony
 * Date: 2019/4/26
 * Time: 9:11
 */

class OauthUserService{

    protected $user = [];
    protected $customer = [];
    protected $baseUrl;
    public function __construct()
    {
        $this->baseUrl = OAUTH_URL;
    }



    public function get_user_info_by_token($token){
        $url = ICE_AG_URL.'starquth/oauth/user';
        $data["access_token"] = $token;
        $re = Curl::getInstance()->get($url,$data)->getBody();
        return $re;
    }
    /*
     * 根据access_token获取用户信息
     */
    public function thirdAuthUser($access_token)
    {
        if(empty($access_token))
        {
            throw new \Exception(ERROR_NO_ACCESS_TOKEN_DESC , ERROR_NO_ACCESS_TOKEN );
        }
        $user_info = app('ICEService')->dispatch('/starquth/oauth/user',['access_token' => $access_token,],[],'GET');
        $this->customer = $user_info;
    }

    public function getCustomerByKey($key = '')
    {
        if(empty($key) || !isset($this->customer[$key]))
        {
            return $this->customer;
        }
        return $this->customer[$key];
    }

    /*
     * 根据access_token获取用户信息
     */
    public function authUserAccessToken($access_token)
    {
        if(empty($access_token)) {
            throw  new Exception("token Can't be NULL");
        }
        $query_header = [
            'Authorization:" Bearer '.$access_token,
        ];
        $user_info = $this->dispatch(
            '/oauth/user',
            array(),
            array(),
            $query_header,
            'GET'
        );
        if($user_info && isset($user_info['content']) && !empty($user_info['content']) && $user_info['code'] == 0)
        {
            $this->user = $user_info['content'];
        }else{
            print_r($user_info);die;
        }
    }

    public function getUserByKey($key = '')
    {
        if(empty($key) || !isset($this->user[$key]))
        {
            return $this->user;
        }
        return $this->user[$key];
    }

    public function dispatch($interface = '', $getParam = array(), $postParam = array(), $queryHeader = array() ,$method = 'GET')
    {
        try {
            $response = $this->request(
            // 拼接请求url，支持post既有get参数又有post参数
                $this->getQueryUrl(
                    $interface,
                    // 处理 queryString 参数
                    $this->getQueryData($getParam)
                ),
                // 处理 post field 参数
                $this->getPostData($postParam),
                $queryHeader,
                $method
            );
        } catch (\Exception $e) {
            $message = $e->getMessage();
            $code = $e->getCode();
            throw new \Exception(
                sprintf(
                    'oauth请求失败：%s[%s]。请重试!',
                    $message ? $message : '连接出错',
                    $code ? $code : '-1'
                ),
                501
            );
        }

        if (!$response) {
            throw new \Exception(
                'OAUTH请求失败,无结果返回: ' . json_encode($response),
                500
            );
        }
        return $response;
    }

    protected function request($queryUrl = '', $queryData = array(), $queryHeader = array(), $method = 'GET')
    {
        $method = strtoupper($method);
        $response = postCurl($queryUrl, $queryData , $queryHeader , $method);
        return $this->parseQueryResponse($response);
    }

    /**
     * 服务 url
     * @param string $interface
     * @param array $queryData
     * @return string
     */
    protected function getQueryUrl($interface = '', $queryData = array())
    {
        $url = sprintf(
            $queryData ? '%s%s/%s?%s' : '%s/%s',
            trim($this->baseUrl, ' /'),
            trim($interface, ' /'),
            $queryData ? http_build_query($queryData) : ''
        );
        return $url;
    }

    /**
     * 处理传递参数
     * @param array $data
     * @return array
     */
    protected function getQueryData($data = array())
    {
        $queryData = array();

        foreach ($data as $key => $item) {
            $queryData[$key] = $item;
        }

        return $queryData;
    }

    /*
     * 处理postData
     */
    protected function getPostData($data = array())
    {
        $parsedData = array();

        if ($data && is_array($data)) {
            foreach ($data as $key => $item) {
                // @ 开头的字段会被认为是文件上传
                // 处理方式，@开头的，先添加空格，然后服务器端去空格
                $pos = strpos($item, '@');
                if ($pos !== false && $pos == 0) {
                    $item = ' ' . $item;
                }

                $parsedData[$key] = $item;
            }
        }

       /// app('log')->info('彩之云Oauth请求参数:' . json_encode($parsedData) . PHP_EOL);


        return $parsedData;
    }

    /**
     * 解析请求返回数据
     * @param string $response
     * @return mixed|string
     */
    protected function parseQueryResponse($response = '')
    {
//        app('log')->info('OAUTH结果:' . $response . PHP_EOL);

        $response = json_decode($response, true);

        return $response;
    }
}